package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.bo.ZhcaInformationAddBo;
import com.ruoyi.system.domain.ZhcaInformation;
import com.ruoyi.system.service.IZhcaInformationService;
import com.ruoyi.system.service.Reptile;
import org.apache.http.Header;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author woo
 * @date 2021/7/29
 */
public abstract class AbstractReptile<T> implements Reptile {
	/**
	 * 1)首页资讯 2)首页资讯第二条 3)走进长安 4)欢乐长安 5)长安应急管理 6)平安长安 7)欢乐巾帼 8)数字长安宏观经济 9)数字长安房地产
	 */
	private Long state;

	public AbstractReptile(Long state) {
		this.state = state;
	}

	@Autowired
	public IZhcaInformationService zhcaInformationService;

	@Override
	public List<ZhcaInformationAddBo> loadInformation() {
		List<T> list = getList();
		if (list == null) {
			return Collections.emptyList();
		}
		return list.stream()
			//跳过重复的
			.filter(this::filter)
			.map(any -> {
				//加载数据
				String data = this.loadData(any);
				//解析数据
				return this.parseData(any, data);
			})
			.filter(ObjectUtil::isNotNull)
			.collect(Collectors.toList());
	}

	/**
	 * 获取列表
	 *
	 * @return
	 */
	public abstract List<T> getList();

	/**
	 * 判断是否跳过
	 * <pre>
	 *     默认方法根据标题排除
	 * </pre>
	 *
	 * @param param 单个原始数据
	 */
	public Boolean filter(T param) {
		String title = parseTitle(param);
		int count = this.zhcaInformationService.count(Wrappers.<ZhcaInformation>lambdaQuery()
			.eq(ZhcaInformation::getTitle, title)
			.eq(ZhcaInformation::getState, this.state)
		);
		//数量大于0,则跳过
		return count == 0;
	}

	public abstract String parseTitle(T param);

	/**
	 * 加载单个详细
	 *
	 * @param param 原始数据
	 * @return
	 */
	public abstract String loadData(T param);

	/**
	 * 解析单个数据为数据库对象
	 *
	 * @param param 原始参数
	 * @param data  加载的详细参数
	 * @return
	 */
	public abstract ZhcaInformationAddBo parseData(T param, String data);

	@Override
	public void save(List<ZhcaInformationAddBo> datas) {
		if (CollUtil.isEmpty(datas)) {
			return;
		}
		datas.forEach(bo -> {
			bo.setState(this.state);
			zhcaInformationService.insertByAddBo(bo);
		});
	}

	/**
	 * 创建一个http请求
	 *
	 * @return
	 */
	public CloseableHttpClient createHttpClient(boolean useHeaders) {
		HttpClientBuilder builder = HttpClientBuilder
			.create();
		if (useHeaders) {
			builder.setDefaultHeaders(this.getDefaultHeaders());
		}
		return builder.build();
	}

	/**
	 * 获取默认的请求头
	 * <pre>
	 *     一般存储一些授权信息
	 * </pre>
	 *
	 * @return
	 */
	public Collection<Header> getDefaultHeaders() {
		return Collections.emptyList();
	}
}
